﻿layui.use(function () {
    var table = layui.table;
    var form = layui.form;
    var $ = layui.jquery;
    let ids = [];
    let check = [];
    var token = localStorage.getItem("token");

    ///列表显示

    $.ajax({
        url: '/Allocate/GetAllocate', // 此处为静态模拟数据，实际使用时需换成真实接口
        type: 'GET',
        data: {
            token: token,
            pageIndex: 1,
            PageSize: 5,
        },
        success: function (res) {
            var resdata = JSON.parse(res);
            console.log(resdata);
            if (resdata != null) {
                // 创建渲染实例
                table.render({
                    elem: '#ID-table-demo-templet',
                    height: '315px',
                    width: '100%',
                    data: resdata.data.list,
                    page: true,
                    cols: [[
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'allocateCode', title: '调拨单号', width: 150, fixed: 'left' },
                        { field: 'productsName', title: '产品名称', width: 150 },
                        { field: 'productsCode', title: '产品编号', width: 150 },
                        { field: 'specs', title: '规格', width: 150 },
                        { field: 'procurementNum', title: '产品数量', width: 150 },
                        { field: 'warehouseName', title: '原仓库', width: 150, },
                        { field: 'storehouseName', title: '原库位名称', width: 150 },
                        { field: 'AllocateStore', title: '调拨仓库', width: 150, },
                        { field: 'storehouseName', title: '调拨库位名称', width: 150 },
                        {
                            field: 'allocateState',
                            title: '状态',
                            width: 120,
                            templet: function (d) {
                                if (d.allocateState == 1) {
                                    return "待审核";
                                }
                                else if (d.allocateState == 2) {
                                    return "审核通过";
                                }
                                else if (d.allocateState == 3) {
                                    return "审核失败";
                                }
                            }


                        },
                        { field: 'updName', title: '审核人', width: 150 },
                        { field: 'updTime', title: '审核时间', width: 150 },
                        // { field: 'allocateId', title: 'id', width: 150 },
                        {
                            field: 'right', title: '操作', width: 300, align: 'center', minWidth: 125, templet: function (d) {
                                return '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete" lay - on="test-page" id = "detail" data-allocateCode="' + d.allocateCode + '" > 查看 </a >'
                                    + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete"   lay - on="test-page"  id="upd" data-allocateCode="' + d.allocateCode + '"   > 编辑</a > '
                                    + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete"   lay - event="moredel"  onclick="Delete()" > 删除</a > '
                                    + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete" lay - on="test-page" id="Approval"   data-allocateId="' + d.allocateId + '"  data-allocateCode="' + d.allocateCode + '"   >审批 </a >'

                            },
                        }


                    ]],
                    limits: [10, 20, 30],
                    toolbar: '#toolbarDemo',
                    defaultToolbar: ['exports'],
                });
            }
            else {
                layer.msg('获取数据失败', { icon: 2 });
            }
        }
    });

    window.onpageshow = function (event) {
        AllocateCode = $('#AllocateCode').val();
        StartDate = $('#StartDate').val();
        EndDate = $('#EndDate').val();
        AllocateState = $('#AllocateState').val();


        $.ajax({
            url: '/Allocate/GetAllocate', // 此处为静态模拟数据，实际使用时需换成真实接口
            type: 'GET',
            data: {
                token: token,
                pageIndex: 1,
                PageSize: 5,
                AllocateCode: AllocateCode,
                StartDate: StartDate,
                EndDate: EndDate,
                AllocateState: AllocateState,
            },
            success: function (res) {
                var resdata = JSON.parse(res);
                console.log(resdata);
                if (resdata != null) {
                    // 创建渲染实例
                    table.render({
                        elem: '#ID-table-demo-templet',
                        data: resdata.data.list,
                        height: '315px',
                        width: '100%',
                        page: true,
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'allocateCode', title: '调拨单号', width: 150, fixed: 'left' },
                            { field: 'productsName', title: '产品名称', width: 150 },
                            { field: 'productsCode', title: '产品编号', width: 150 },
                            { field: 'specs', title: '规格', width: 150 },
                            { field: 'procurementNum', title: '产品数量', width: 150 },
                            { field: 'warehouseName', title: '原仓库', width: 150, },
                            { field: 'storehouseName', title: '原库位名称', width: 150 },
                            {
                                field: 'allocateStore', title: '调拨仓库', width: 150,
                                templet: function (d) {
                                    if (d.allocateStore == 1) {
                                        return "采购收货入库";
                                    }
                                    else if (d.allocateStore == 2) {
                                        return "销售退货入库";
                                    }
                                    else if (d.allocateStore == 3) {
                                        return "生产产品入库";
                                    }
                                }
                            },
                            { field: 'storehouseName', title: '调拨库位名称', width: 150 },
                            {
                                field: 'allocateState',
                                title: '状态',
                                width: 120,
                                templet: function (d) {
                                    if (d.allocateState == 1) {
                                        return "待审核";
                                    }
                                    else if (d.allocateState == 2) {
                                        return "审核通过";
                                    }
                                    else if (d.allocateState == 3) {
                                        return "审核失败";
                                    }
                                }
                            },
                            { field: 'updName', title: '审核人', width: 150 },
                            { field: 'updTime', title: '审核时间', width: 150 },
                            //{ field: 'allocateId', title: 'id', width: 150 },
                            {
                                field: 'right', title: '操作', width: 300, align: 'center', minWidth: 125, templet: function (d) {
                                    return '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete" lay - on="test-page" id = "detail" data-allocateCode="' + d.allocateCode + '" > 查看 </a >'
                                        + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete"   lay - on="test-page"  id="upd" data-allocateCode="' + d.allocateCode + '"   > 编辑</a > '
                                        + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete"   lay - event="moredel"  onclick="Delete()" > 删除</a > '
                                        + '<a class="layui-btn layui-btn-xs layui-icon layui-icon-delete" lay - on="test-page" id="Approval"   data-allocateId="' + d.allocateId + '"  data-allocateCode="' + d.allocateCode + '"   >审批 </a >'

                                },
                            }


                        ]],
                        limits: [10, 20, 30],
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                    });
                }
                else {
                    layer.msg('获取数据失败', { icon: 2 });
                }
            }
        });
    };

    window.Delete = function Delete() {
        var ids = [];
        var check = table.checkStatus('ID-table-demo-templet').data;
        for (var i = 0; i < check.length; i++) {
            ids.push(check[i].allocateId);
        }
        if (ids.length === 0) {
            layer.msg('请选择要删除的行', { icon: 2 });
            return;
        }
        console.log(ids);

        layer.confirm('确认删除？', {
            btn: ['确认', '取消']
        }, function () {
            $.ajax({
                url: '/Allocate/DelAllocate',
                type: 'post',
                data: {
                    token: token,
                    AllocateId: ids,  // 发送为JSON字符串
                    DelName: localStorage.getItem("UserName"),
                },
                success: function (res) {
                    console.log(res);
                    var resdata = JSON.parse(res);
                    if (resdata.code === 200) {
                        layer.msg('删除成功', { icon: 1 });
                        window.location.reload();
                    } else {
                        layer.msg('删除失败', { icon: 2 });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error("AJAX Error: ", textStatus, errorThrown);
                    layer.msg('请求失败，请重试', { icon: 2 });
                }
            });
        });
    }               //查看详情
    $(document).on('click', '#detail', function () {
        var allocateCode = $(this).attr('data-allocateCode');
        console.log(allocateCode);
        //打开弹框
        var index = layer.open({
            type: 1,
            area: ['800px', '500px'], // 宽高
            content: '<table style="width:650px;height:300px; margin-left:45px">' +
                '<tr>' +
                '<td>调拨单号:</td>' +
                '<td id="allocateCode"></td>' +
                '<td style="width:100px">单据状态：</td>' +
                '<td id="allocateState" style="width:100px"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>关联订单号：</td>' +
                '<td id="morderNumber"></td>' +
                '<td>制单人：</td>' +
                '<td id="makePerson"></td>' +
                '<td>制单日期：</td>' +
                '<td id="markTime"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>备注：</td>' +
                '<td id="aRremark"></td>' +
                '<td>审核原因：</td>' +
                '<td id="reasonReview"></td>' +
                '</tr>' +
                '</table>' +
                '<table class= "layui-table" id="InProductId-Id" >' +
                '<thead>' +
                '<tr>' +
                '<col width="150">' +
                '<col>' +
                '</tr>' +
                '</thead>' +
                '</table>',

            success: function (lay, index) {
                form.render();
            }
        });
        var obj = {
            Token: token,
            AllocateCode: allocateCode,
        }
        $.ajax({
            url: '/Allocate/GetInquireAllocate',
            type: "get",
            data: obj,
            success: (ress) => {
                var res = JSON.parse(ress);
                console.log(res);
                // 渲染表格
                table.render({
                    elem: '#InProductId-Id',
                    cols: [[
                        { field: 'productsCode', title: '产品编号', width: 150 },
                        { field: 'productsName', title: '产品名称', width: 150 },
                        { field: 'specs', title: '产品规格', width: 150 },
                        { field: 'procurementNum', title: '数量', width: 150 },
                        { field: 'storehouseName', title: '当前库位', width: 120, },
                        {
                            field: 'allocateStore', title: '调拨仓库', width: 120, templet: function (d) {
                                switch (d.allocateStore) {
                                    case 1:
                                        return '报损仓库';
                                    case 2:
                                        return '报损库位';
                                    case 3:
                                        return '默认库位';
                                    default:
                                        return '未知类型';
                                }
                            }
                        },

                    ]],
                    data: res.data,  // 数据源
                });
                //反填报损信息
                $(res.data).each(function () {
                    console.log(res.data[0])
                    $("#allocateCode").text(this.allocateCode);
                    $("#productsID").text(this.productsID);
                    $("#productsCode").text(this.productsCode);
                    $("#productsName").text(this.productsName);
                    $("#specs").text(this.specs);
                    $("#procurementNum").text(this.procurementNum);
                    $("#warehouseId").text(this.warehouseId);
                    $("#warehouseName").text(this.warehouseName);
                    $("#storehouseName").text(this.storehouseName);
                    $("#allocateStore").text(this.allocateStore);
                    $("#allocateState").text(this.allocateState);
                    $("#updName").text(this.updName);
                    $("#morderNumber").text(this.morderNumber);
                    //反填日期框
                    var da = new Date(this.updTime);
                    // 获取年、月、日
                    var year = da.getFullYear();
                    var month = (da.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                    var day = da.getDate().toString().padStart(2, '0');  // 补充两位数字
                    // 获取小时（0-23）
                    var hours = da.getHours();
                    // 获取分钟（0-59）
                    var minutes = da.getMinutes();
                    // 获取秒（0-59）
                    var seconds = da.getSeconds();
                    var formattedHours = hours.toString().padStart(2, '0');
                    var formattedMinutes = minutes.toString().padStart(2, '0');
                    var formattedSeconds = seconds.toString().padStart(2, '0');
                    var timeString = formattedHours + ':' + formattedMinutes + ':' + formattedSeconds;
                    // 拼接成 "yyyy-MM-dd" 格式
                    var formattedDate = `${year}-${month}-${day} ${timeString}`;
                    $("#updTime").text(formattedDate);
                    $("#makePerson").text(this.makePerson);
                    $("#markTime").text(this.markTime);
                    $("#aRremark").text(this.aRremark);
                    $("#reasonReview").text(this.reasonReview);


                    if (this.allocateState == 1) {
                        $("#allocateState").text("待审核")
                    }
                    if (this.allocateState == 2) {
                        $("#allocateState").text("审核成功")
                    }
                    if (this.allocateState == 3) {
                        $("#allocateState").text("审核失败")
                    }

                })





            }
        });

    });
    //编辑
    $(document).on('click', '#upd', function () {
        var allocateCode = $(this).attr('data-allocateCode');
        console.log(allocateCode);
        location.href = "/Allocate/UpdAllocate?allocateCode=" + allocateCode;
    });
    //审批
    $(document).on('click', '#Approval', function () {
        var allocateCode = $(this).attr('data-allocateCode');
        console.log(allocateCode);
        var allocateId = $(this).attr('data-allocateId');
        console.log(allocateId);
        //打开弹框
        var index = layer.open({
            type: 1,
            area: ['800px', '500px'], // 宽高
            content: '<table style="width:650px;height:300px; margin-left:45px">' +
                '<tr>' +
                '<td>调拨单号:</td>' +
                '<td id="allocateCode"></td>' +
                '<td style="width:100px">单据状态：</td>' +
                '<td id="allocateState" style="width:100px"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>关联订单号：</td>' +
                '<td id="morderNumber"></td>' +
                '<td>制单人：</td>' +
                '<td id="makePerson"></td>' +
                '<td>制单日期：</td>' +
                '<td id="markTime"></td>' +
                '</tr>' +
                '<tr>' +
                '<td>备注：</td>' +
                '<td id="aRremark"></td>' +
                '<td>审核原因：</td>' +
                '<td >' +
                '<input type="text" id="reasonReview" style="width:200px;height:100px;"></textarea>' +
                '</td>' +
                '</tr>' +
                '</table>' +
                '<table class= "layui-table" id="InProductId-Id" >' +
                '<thead>' +
                '<tr>' +
                '<col width="150">' +
                '<col>' +
                '</tr>' +
                '</thead>' +
                '</table>' +
                '<input type=button value="审核通过" id="pass" style="float:right;margin-top:20px;width:100px;height:30px;background-color:green;color:white;border:none;border-radius:5px;"   >' +
                '<input type=button value="审核失败" id="fail" style="float:right;margin-top:20px;width:100px;height:30px;background-color:red;color:white;border:none;border-radius:5px;">'

            ,

            success: function (lay, index) {
                form.render();
            }
        });
        var obj = {
            Token: token,
            AllocateCode: allocateCode,
        }
        $.ajax({
            url: '/Allocate/GetInquireAllocate',
            type: "get",
            data: obj,
            success: (ress) => {
                var res = JSON.parse(ress);
                console.log(res);
                // 渲染表格
                table.render({
                    elem: '#InProductId-Id',
                    cols: [[
                        { field: 'productsCode', title: '产品编号', width: 150 },
                        { field: 'productsName', title: '产品名称', width: 150 },
                        { field: 'specs', title: '产品规格', width: 150 },
                        { field: 'procurementNum', title: '数量', width: 150 },
                        { field: 'storehouseName', title: '当前库位', width: 120, },
                        {
                            field: 'allocateStore', title: '调拨仓库', width: 120, templet: function (d) {
                                switch (d.allocateStore) {
                                    case 1:
                                        return '报损仓库';
                                    case 2:
                                        return '报损库位';
                                    case 3:
                                        return '默认库位';
                                    default:
                                        return '未知类型';
                                }
                            }
                        },

                    ]],
                    data: res.data,  // 数据源
                });
                //反填报损信息
                $(res.data).each(function () {
                    console.log(res.data[0])
                    $("#allocateCode").text(this.allocateCode);
                    $("#productsID").text(this.productsID);
                    $("#productsCode").text(this.productsCode);
                    $("#productsName").text(this.productsName);
                    $("#specs").text(this.specs);
                    $("#procurementNum").text(this.procurementNum);
                    $("#warehouseId").text(this.warehouseId);
                    $("#warehouseName").text(this.warehouseName);
                    $("#storehouseName").text(this.storehouseName);
                    $("#allocateStore").text(this.allocateStore);
                    $("#allocateState").text(this.allocateState);
                    $("#updName").text(this.updName);
                    $("#morderNumber").text(this.morderNumber);
                    //反填日期框
                    var da = new Date(this.updTime);
                    // 获取年、月、日
                    var year = da.getFullYear();
                    var month = (da.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                    var day = da.getDate().toString().padStart(2, '0');  // 补充两位数字
                    // 获取小时（0-23）
                    var hours = da.getHours();
                    // 获取分钟（0-59）
                    var minutes = da.getMinutes();
                    // 获取秒（0-59）
                    var seconds = da.getSeconds();
                    var formattedHours = hours.toString().padStart(2, '0');
                    var formattedMinutes = minutes.toString().padStart(2, '0');
                    var formattedSeconds = seconds.toString().padStart(2, '0');
                    var timeString = formattedHours + ':' + formattedMinutes + ':' + formattedSeconds;
                    // 拼接成 "yyyy-MM-dd" 格式
                    var formattedDate = `${year}-${month}-${day} ${timeString}`;
                    $("#updTime").text(formattedDate);
                    $("#makePerson").text(this.makePerson);
                    $("#markTime").text(this.markTime);
                    $("#aRremark").text(this.aRremark);
                    $("#reasonReview").text(this.reasonReview);


                    if (this.allocateState == 1) {
                        $("#allocateState").text("待审核")
                    }
                    if (this.allocateState == 2) {
                        $("#allocateState").text("审核成功")
                    }
                    if (this.allocateState == 3) {
                        $("#allocateState").text("审核失败")
                    }

                })





            }
        });
        //审核通过
        $(document).on('click', '#pass', function () {
            ReasonReview = $("#reasonReview").val()
            console.log(allocateId);
            var obj = {
                Token: token,
                id: allocateId,
                state: 2,
                Updname: localStorage.getItem("UserName") || '',
                Updtime: new Date().toLocaleString(),
                ReasonReview: ReasonReview
            }
            $.ajax({
                url: '/Allocate/UpdAllocateStateList',
                type: "post",
                data: obj,
                success: (ress) => {
                    var res = JSON.parse(ress);
                    console.log(res);
                    if (res.code === 200) {
                        layer.msg('审核成功', { icon: 1 });
                        window.location.reload();
                    } else {
                        layer.msg('审核失败', { icon: 2 });
                    }
                }
            });



        });
        //审核不通过
        $(document).on('click', '#fail', function () {
            ReasonReview = $("#reasonReview").val()
            console.log(allocateId);
            var obj = {
                Token: token,
                id: allocateId,
                state: 3,
                Updname: localStorage.getItem("UserName") || '',
                Updtime: new Date().toLocaleString(),
                ReasonReview: ReasonReview
            }
            $.ajax({
                url: '/Allocate/UpdAllocateStateList',
                type: "post",
                data: obj,
                success: (ress) => {
                    var res = JSON.parse(ress);
                    console.log(res);
                    if (res.code === 200) {
                        layer.msg('审核成功', { icon: 1 });
                        window.location.reload();
                    } else {
                        layer.msg('审核失败', { icon: 2 });
                    }
                }
            });



        });



    });

});
